//
//  WithDrawVC.swift
//  kxf
//  提现
//  Created by Mac on 2024/3/12.
//

import Foundation
import UIKit
import MCToast

class WithDrawVC: WHBaseViewVC {
    
    var totalMoney = "0.00"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        initUI()
        
        sendSettleBankMSgRequest()
        sendWithDrawConfigRequest()
    }
    lazy var bankCardTitleVm : RegisterViewHeadTitleVM = {
        let vm = RegisterViewHeadTitleVM.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(10), width: 0, height: 0))
        vm.titleLabel.text = "到账银行卡"
        return vm
    }()
    lazy var bankCardLabel : UILabel = {
        let lab = UILabel()
        lab.textColor = .COLOR_TEXT_BLACK666
        lab.font = .systemFont(ofSize: 16, weight: .regular)
//        lab.text = "交通银行储蓄卡（1213）"
        lab.adjustsFontSizeToFitWidth = true
        
        return lab
    }()
    lazy var whiteView : UIView = {
        let vi = UIView()
        vi.layer.cornerRadius = kFitWidth(8)
        vi.clipsToBounds = true
        vi.backgroundColor = .white
        vi.isUserInteractionEnabled = true
        
        return vi
    }()
    lazy var moneyTitleVm : RegisterViewHeadTitleVM = {
        let vm = RegisterViewHeadTitleVM.init(frame: .zero)
        vm.titleLabel.text = "提现金额"
        return vm
    }()
    lazy var moneLab : UILabel = {
        let lab = UILabel()
        lab.text = "¥"
        lab.textColor = .COLOR_TEXT_BLACK666
        lab.font = .systemFont(ofSize: 15, weight: .bold)
        
        return lab
    }()
    lazy var moneyLineView : UIView = {
        let vi = UIView()
        vi.backgroundColor = .THEME
        
        return vi
    }()
    lazy var moneyTextField : UITextField = {
        let text = UITextField()
        text.placeholder = "0.00"
        text.textColor = .COLOR_TEXT_BLACK666
        text.font = .systemFont(ofSize: 24, weight: .medium)
        text.keyboardType = .decimalPad
        text.delegate = self
        
        return text
    }()
    lazy var lineView : UIView = {
        let vi = UIView()
        vi.backgroundColor = .COLOR_LIGHT_GREY
        
        return vi
    }()
    lazy var balanceTotleLabel : YYLabel = {
        let lab = YYLabel()
        lab.font = .systemFont(ofSize: 15, weight: .regular)
        lab.textColor = .black
        
        let attr = NSMutableAttributedString.init(string: "可用余额")
        let twoString = NSMutableAttributedString.init(string: "¥0.00")
        twoString.yy_font = .systemFont(ofSize: 15, weight: .medium)
        
        attr.append(twoString)
        
        lab.attributedText = attr
        return lab
    }()
    lazy var withdrawAllBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("全部提现", for: .normal)
        btn.setTitleColor(.THEME, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .regular)
        
        btn.addTarget(self, action: #selector(allMoneyTiXianAction), for: .touchUpInside)
        
        return btn
    }()
    lazy var settleMoneyLabel : YYLabel = {
        let lab = YYLabel()
        lab.font = .systemFont(ofSize: 12, weight: .regular)
        lab.textColor = .black
        
        let attr = NSMutableAttributedString.init(string: "待结算")
        let twoString = NSMutableAttributedString.init(string: "¥34.53")
        twoString.yy_font = .systemFont(ofSize: 15, weight: .regular)
        
        attr.append(twoString)
        
        lab.attributedText = attr
        return lab
    }()
    lazy var settleTipsLabel : UILabel = {
        let lab = UILabel()
        lab.text = "结算周期：月初结算收益"
        lab.textColor = .COLOR_TEXT_BLACK999
        lab.font = .systemFont(ofSize: 12, weight: .regular)
        
        return lab
    }()
    lazy var withDrawMoneyLabel : YYLabel = {
        let lab = YYLabel()
        lab.font = .systemFont(ofSize: 12, weight: .regular)
        lab.textColor = .black
        
        let attr = NSMutableAttributedString.init(string: "可提现余额")
        let twoString = NSMutableAttributedString.init(string: "¥34.53")
        twoString.yy_font = .systemFont(ofSize: 15, weight: .medium)
        
        attr.append(twoString)
        
        lab.attributedText = attr
        return lab
    }()
    lazy var withdrawTipsLabel : UILabel = {
        let lab = UILabel()
        lab.text = "提现时间：每月20号开放"
        lab.textColor = .COLOR_TEXT_BLACK999
        lab.font = .systemFont(ofSize: 12, weight: .regular)
        
        return lab
    }()
    lazy var withDrawBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("确认提现", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.layer.cornerRadius = kFitWidth(24)
        btn.clipsToBounds = true
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .regular)
        btn.backgroundColor = .clear
        btn.setBackgroundImage(UIImage.init(named: "button_theme_bg"), for: .normal)
        
        btn.addTarget(self, action: #selector(withDrawAction), for: .touchUpInside)
        
        return btn
    }()
}

extension WithDrawVC{
    @objc func allMoneyTiXianAction() {
        moneyTextField.text = self.totalMoney
    }
    @objc func withDrawAction(){
        let money = moneyTextField.text ?? "0"
        if money.floatValue > self.totalMoney.floatValue{
            MCToast.mc_text("提现金额不能超过可用余额（\(self.totalMoney)）")
            return
        }
        if money.floatValue < 1.0{
            MCToast.mc_text("提现金额不能小于1元")
            return
        }
        sendWithDrawRequest()
    }
}

extension WithDrawVC{
    func initUI() {
        initNavi(titleStr: "提现")
        
        view.backgroundColor = .COLOR_LIGHT_GREY
        
        view.addSubview(bankCardTitleVm)
        bankCardTitleVm.addSubview(bankCardLabel)
        
        view.addSubview(whiteView)
        whiteView.addSubview(moneyTitleVm)
        whiteView.addSubview(moneLab)
        whiteView.addSubview(moneyLineView)
        whiteView.addSubview(moneyTextField)
        whiteView.addSubview(lineView)
        whiteView.addSubview(balanceTotleLabel)
        whiteView.addSubview(withdrawAllBtn)
//        whiteView.addSubview(settleMoneyLabel)
//        whiteView.addSubview(settleTipsLabel)
//        whiteView.addSubview(withDrawMoneyLabel)
//        whiteView.addSubview(withdrawTipsLabel)
        
        view.addSubview(withDrawBtn)
        
        setConstrait()
    }
    func setConstrait() {
        bankCardLabel.snp.makeConstraints { make in
            make.centerY.lessThanOrEqualToSuperview()
            make.right.equalTo(kFitWidth(-10))
        }
        whiteView.snp.makeConstraints { make in
            make.left.width.equalToSuperview()
            make.top.equalTo(bankCardTitleVm.snp.bottom).offset(kFitWidth(10))
            make.height.equalTo(kFitWidth(151))
        }
        moneyLineView.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(50))
            make.top.equalTo(kFitWidth(63))
            make.width.equalTo(kFitWidth(1))
            make.height.equalTo(kFitWidth(30))
        }
        moneLab.snp.makeConstraints { make in
            make.right.equalTo(moneyLineView.snp.left).offset(kFitWidth(-3))
            make.centerY.lessThanOrEqualTo(moneyLineView)
        }
        moneyTextField.snp.makeConstraints { make in
            make.left.equalTo(moneyLineView.snp.right).offset(kFitWidth(4))
            make.centerY.lessThanOrEqualTo(moneyLineView)
            make.width.equalTo(kFitWidth(240))
            make.height.equalTo(kFitWidth(30))
        }
        lineView.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(30))
            make.top.equalTo(moneyTextField.snp.bottom).offset(kFitWidth(2))
            make.width.equalTo(kFitWidth(200))
            make.height.equalTo(kFitWidth(0.4))
        }
        balanceTotleLabel.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(36))
            make.top.equalTo(lineView.snp.bottom).offset(kFitWidth(10))
            make.height.equalTo(kFitWidth(19))
            
        }
        withdrawAllBtn.snp.makeConstraints { make in
            make.left.equalTo(balanceTotleLabel.snp.right).offset(kFitWidth(8))
            make.centerY.lessThanOrEqualTo(balanceTotleLabel)
        }
//        settleMoneyLabel.snp.makeConstraints { make in
//            make.left.equalTo(balanceTotleLabel)
//            make.top.equalTo(balanceTotleLabel.snp.bottom).offset(kFitWidth(7))
//            
//        }
//        settleTipsLabel.snp.makeConstraints { make in
//            make.left.equalTo(settleMoneyLabel.snp.right).offset(kFitWidth(7))
//            make.centerY.lessThanOrEqualTo(settleMoneyLabel)
//        }
//        withDrawMoneyLabel.snp.makeConstraints { make in
//            make.left.equalTo(balanceTotleLabel)
//            make.top.equalTo(settleMoneyLabel.snp.bottom).offset(kFitWidth(7))
//        }
//        withdrawTipsLabel.snp.makeConstraints { make in
//            make.left.equalTo(withDrawMoneyLabel.snp.right).offset(kFitWidth(8))
//            make.centerY.lessThanOrEqualTo(withDrawMoneyLabel)
//        }
        withDrawBtn.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.width.equalTo(kFitWidth(316))
            make.height.equalTo(kFitWidth(48))
            make.top.equalTo(whiteView.snp.bottom).offset(kFitWidth(146))
        }
    }
}

extension WithDrawVC{
    func sendSettleBankMSgRequest() {
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().GET(urlString: URL_settleBank_Agent) { responseObject in
            DLLog(message: "\(responseObject)")
            
            if responseObject["code"]as? Int ?? 0 == 200{
                let dataArr = responseObject["data"]as? NSArray ?? []
                if dataArr.count > 0 {
                    let dataObj = dataArr[0]as? NSDictionary ?? [:]
                    let bankNo = "\(dataObj["bankCardId"]as? String ?? "0000")"
                    self.bankCardLabel.text = "\(dataObj["bankName"]as? String ?? "")储蓄卡（\(bankNo.mc_cutToSuffix(from: bankNo.count-4))）"
                }else{
                    self.presentAlertVcNoAction(title: "未查询到结算卡信息", viewController: self)
                }
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "网络异常，请稍后重试")", viewController: self)
            }
        }
    }
    func sendWithDrawConfigRequest(){
        MCToast.mc_loading()
        let param = ["agentid":"\(UserModel.shared.agentId)",
                     "serviceType":"2"]
        WHNetworkUtil.shareManager().POST(urlString: URL_withDraw_config, parameters: param as [String:AnyObject]) { responseObject in
            DLLog(message: "\(responseObject)")
            
            let dataObj = responseObject["data"]as? NSDictionary ?? [:]
            
            let attr = NSMutableAttributedString.init(string: "可用余额")
            
            self.totalMoney = "\(dataObj["amount"]as? Double ?? 0.00)"
            
            let twoString = NSMutableAttributedString.init(string: "¥\(self.totalMoney)")
            twoString.yy_font = .systemFont(ofSize: 15, weight: .medium)
            attr.append(twoString)
            self.balanceTotleLabel.attributedText = attr
            
        }
    }
    func sendWithDrawRequest() {
        MCToast.mc_loading()
        let param = ["agentid":"\(UserModel.shared.agentId)",
                     "serviceType":"2",
                     "money":"\(moneyTextField.text ?? "0")"]
        WHNetworkUtil.shareManager().POST(urlString: URL_withDraw, parameters: param as [String:AnyObject]) { responseObject in
            DLLog(message: "\(responseObject)")
            self.presentAlertVcNoAction(title: "提现申请成功！", viewController: self)
            self.sendWithDrawConfigRequest()
        }
    }
}


extension WithDrawVC:UITextFieldDelegate{
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == "" {
            return true
        }
        if string == "."{
            let str = textField.text ?? ""
            if str.contains("."){
                return false
            }
            if str.count == 0{
                return false
            }
        }
        if textField.text?.count ?? 0 > 10{
            return false
        }
        if let numArr = textField.text?.components(separatedBy: "."){
            if numArr.count >= 2{
                let decimal = numArr[1]as? String ?? ""
                if decimal.count >= 2{
                    return false
                }
            }
        }
        return true
    }
}
